<!-- 志愿服务统计分析 -->
<template>
  <div class="statistics-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="title">
        <el-icon><DataLine /></el-icon>
        <span>志愿服务统计分析</span>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <el-row :gutter="24">
      <el-col :span="8">
        <el-card class="statistic-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>总体服务统计</span>
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
              />
            </div>
          </template>
          <div class="statistic-content">
            <div class="statistic-item">
              <div class="label">服务总时长</div>
              <div class="value">{{ dateRangeStats.totalServiceHours || 0 }} 小时</div>
            </div>
            <div class="statistic-item">
              <div class="label">参与人数</div>
              <div class="value">{{ dateRangeStats.participantCount || 0 }} 人</div>
            </div>
            <div class="statistic-item">
              <div class="label">活动数量</div>
              <div class="value">{{ dateRangeStats.activityCount || 0 }} 个</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="statistic-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>志愿者服务排行</span>
              <el-select v-model="rankingLimit" placeholder="显示数量" @change="fetchRankingData">
                <el-option :value="5" label="Top 5" />
                <el-option :value="10" label="Top 10" />
                <el-option :value="20" label="Top 20" />
              </el-select>
            </div>
          </template>
          <div class="ranking-list">
            <div v-for="(item, index) in rankingData" :key="item.volunteerId" class="ranking-item">
              <span class="rank">{{ index + 1 }}</span>
              <span class="name">{{ item.volunteerName }}</span>
              <span class="hours">{{ item.serviceHours }}小时</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="8">
        <el-card class="statistic-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>服务类型分布</span>
            </div>
          </template>
          <div ref="serviceTypeChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 活动分析区域 -->
    <el-row :gutter="24" class="mt-4">
      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>活动参与分析</span>
              <el-select v-model="selectedActivityId" placeholder="选择活动" @change="fetchActivityParticipation">
                <el-option
                  v-for="activity in activities"
                  :key="activity.id"
                  :label="activity.title"
                  :value="activity.id"
                />
              </el-select>
            </div>
          </template>
          <div v-if="selectedActivityId">
            <div class="participation-stats">
              <div class="stat-item">
                <div class="label">参与人数</div>
                <div class="value">{{ activityStats.participantCount || 0 }}</div>
              </div>
              <div class="stat-item">
                <div class="label">总服务时长</div>
                <div class="value">{{ activityStats.totalServiceHours || 0 }}小时</div>
              </div>
              <div class="stat-item">
                <div class="label">出勤率</div>
                <div class="value">{{ activityStats.attendanceRate || 0 }}%</div>
              </div>
            </div>
            <div ref="participationChart" class="chart-container"></div>
          </div>
          <el-empty v-else description="请选择活动" />
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>志愿者服务详情</span>
              <el-input
                v-model="selectedVolunteerId"
                placeholder="输入志愿者ID"
                @change="fetchVolunteerStats"
              >
                <template #append>
                  <el-button @click="fetchVolunteerStats">查询</el-button>
                </template>
              </el-input>
            </div>
          </template>
          <div v-if="volunteerStats.totalServiceHours !== undefined" class="volunteer-stats">
            <div class="stat-item">
              <div class="label">总服务时长</div>
              <div class="value">{{ volunteerStats.totalServiceHours }}小时</div>
            </div>
            <div class="stat-item">
              <div class="label">参与活动次数</div>
              <div class="value">{{ volunteerStats.totalActivityCount }}次</div>
            </div>
            <div class="stat-item">
              <div class="label">本月服务时长</div>
              <div class="value">{{ volunteerStats.monthServiceHours }}小时</div>
            </div>
          </div>
          <el-empty v-else description="请输入志愿者ID查询" />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { DataLine } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {
  getVolunteerStatistics,
  getActivityStatistics,
  getDateRangeStatistics,
  getVolunteerRanking,
  getActivityParticipation,
  getServiceTypeDistribution
} from '@/api/statistics'
import { getActivityList } from '@/api/activity'

// 日期范围
const dateRange = ref([])
const dateRangeStats = ref({})

// 排行榜数据
const rankingLimit = ref(10)
const rankingData = ref([])

// 活动相关
const selectedActivityId = ref('')
const activities = ref([])
const activityStats = ref({})

// 志愿者统计
const selectedVolunteerId = ref('')
const volunteerStats = ref({})

// 图表实例
const serviceTypeChart = ref(null)
const participationChart = ref(null)
let serviceTypeChartInstance = null
let participationChartInstance = null

// 获取日期范围统计
const handleDateRangeChange = async () => {
  if (!dateRange.value || dateRange.value.length !== 2) return
  try {
    const [startDate, endDate] = dateRange.value
    const res = await getDateRangeStatistics({ startDate, endDate })
    if (res.code === 200) {
      dateRangeStats.value = res.data
    }
  } catch (error) {
    console.error('获取日期范围统计失败：', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取排行榜数据
const fetchRankingData = async () => {
  try {
    const res = await getVolunteerRanking({ limit: rankingLimit.value })
    if (res.code === 200) {
      rankingData.value = res.data
    }
  } catch (error) {
    console.error('获取排行榜数据失败：', error)
    ElMessage.error('获取排行榜数据失败')
  }
}

// 获取活动参与情况
const fetchActivityParticipation = async () => {
  if (!selectedActivityId.value) return
  try {
    const [statsRes, participationRes] = await Promise.all([
      getActivityStatistics(selectedActivityId.value),
      getActivityParticipation(selectedActivityId.value)
    ])
    if (statsRes.code === 200) {
      activityStats.value = statsRes.data
    }
    if (participationRes.code === 200) {
      updateParticipationChart(participationRes.data)
    }
  } catch (error) {
    console.error('获取活动参与情况失败：', error)
    ElMessage.error('获取活动参与情况失败')
  }
}

// 获取志愿者统计
const fetchVolunteerStats = async () => {
  if (!selectedVolunteerId.value) {
    ElMessage.warning('请输入志愿者ID')
    return
  }
  try {
    const res = await getVolunteerStatistics(selectedVolunteerId.value)
    if (res.code === 200) {
      volunteerStats.value = res.data
    }
  } catch (error) {
    console.error('获取志愿者统计失败：', error)
    ElMessage.error('获取志愿者统计失败')
  }
}

// 获取活动列表
const fetchActivities = async () => {
  try {
    const res = await getActivityList()
    if (res.code === 200) {
      activities.value = res.data?.list || []
    }
  } catch (error) {
    console.error('获取活动列表失败：', error)
    ElMessage.error('获取活动列表失败')
  }
}

// 初始化服务类型分布图表
const initServiceTypeChart = () => {
  if (!serviceTypeChart.value) return
  serviceTypeChartInstance = echarts.init(serviceTypeChart.value)
}

// 更新服务类型分布图表
const updateServiceTypeChart = (data) => {
  if (!serviceTypeChartInstance) return
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '14',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: data.map(item => ({
          name: item.serviceType,
          value: item.participantCount
        }))
      }
    ]
  }
  serviceTypeChartInstance.setOption(option)
}

// 初始化参与情况图表
const initParticipationChart = () => {
  if (!participationChart.value) return
  participationChartInstance = echarts.init(participationChart.value)
}

// 更新参与情况图表
const updateParticipationChart = (data) => {
  if (!participationChartInstance) return
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['签到人数']
    },
    xAxis: {
      type: 'category',
      data: Object.keys(data.timeDistribution)
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '签到人数',
        type: 'line',
        smooth: true,
        data: Object.values(data.timeDistribution)
      }
    ]
  }
  participationChartInstance.setOption(option)
}

// 获取服务类型分布数据
const fetchServiceTypeDistribution = async () => {
  try {
    const res = await getServiceTypeDistribution()
    if (res.code === 200) {
      updateServiceTypeChart(res.data)
    }
  } catch (error) {
    console.error('获取服务类型分布失败：', error)
    ElMessage.error('获取服务类型分布失败')
  }
}

// 重绘图表的处理函数
const handleResize = () => {
  serviceTypeChartInstance?.resize()
  participationChartInstance?.resize()
}

// 页面初始化
onMounted(() => {
  initServiceTypeChart()
  initParticipationChart()
  fetchRankingData()
  fetchServiceTypeDistribution()
  fetchActivities()

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除事件监听
  window.removeEventListener('resize', handleResize)
  // 销毁图表实例
  serviceTypeChartInstance?.dispose()
  participationChartInstance?.dispose()
})
</script>

<style scoped>
.statistics-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100%;
}

.page-header {
  margin-bottom: 24px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
}

.title {
  display: flex;
  align-items: center;
  font-size: 24px;
  font-weight: 600;
  color: #fff;
}

.title .el-icon {
  margin-right: 12px;
  font-size: 28px;
}

.statistic-card {
  margin-bottom: 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.statistic-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.statistic-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.statistic-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  font-size: 20px;
  font-weight: 600;
  color: #1890ff;
}

.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.ranking-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background-color: #fafafa;
  border-radius: 4px;
}

.rank {
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #1890ff;
  color: #fff;
  border-radius: 50%;
  margin-right: 12px;
  font-weight: bold;
}

.name {
  flex: 1;
  margin-right: 12px;
}

.hours {
  color: #1890ff;
  font-weight: 500;
}

.participation-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.volunteer-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  background-color: #fafafa;
  border-radius: 8px;
}

.mt-4 {
  margin-top: 24px;
}

:deep(.el-card__header) {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-empty) {
  padding: 40px 0;
}
</style> 